package com.example.hot100;

import java.util.*;

/**
 * 给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
 * <p>
 * 给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
 * <p>
 * 示例 1：
 * 输入：digits = "23"
 * 输出：["ad","ae","af","bd","be","bf","cd","ce","cf"]
 * <p>
 * 示例 2：
 * 输入：digits = ""
 * 输出：[]
 */
public class Leetcode17_LetterCombinations {
    public static void main(String[] args) {
        String digits = "23";
        List<String> res = new Solution().letterCombinations(digits);
        System.out.println(res);
    }

    static class Solution {
        public List<String> letterCombinations(String digits) {
            List<String> res = new ArrayList<>();
            Deque<Character> singleRes = new LinkedList<>();
            if (digits.length() == 0) return res;
            char[] chars = digits.toCharArray();
            Map<Character, List<Character>> map = new HashMap<>();
            map.put('2', Arrays.asList('a', 'b', 'c'));
            map.put('3', Arrays.asList('d', 'e', 'f'));
            map.put('4', Arrays.asList('g', 'h', 'i'));
            map.put('5', Arrays.asList('j', 'k', 'l'));
            map.put('6', Arrays.asList('m', 'n', 'o'));
            map.put('7', Arrays.asList('p', 'q', 'r', 's'));
            map.put('8', Arrays.asList('t', 'u', 'v'));
            map.put('9', Arrays.asList('w', 'x', 'y', 'z'));
            backTrack(chars, new StringBuilder(), res, 0, map);

            return res;
        }

        private void backTrack(char[] chars, StringBuilder singleRes, List<String> res,
                               int index, Map<Character, List<Character>> map) {
            if (index == chars.length) {
                res.add(singleRes.toString());
                return;
            }

            List<Character> values = map.get(chars[index]);
            for (int i = 0; i < values.size(); i++) {
                singleRes.append(values.get(i));
                backTrack(chars, singleRes, res, index + 1, map);
                singleRes.deleteCharAt(index);
            }

        }
    }
}
